<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="计划编号" prop="planId">
        <el-input
          v-model="queryParams.planId"
          placeholder="请输入计划编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料编号" prop="materialId">
        <el-input
          v-model="queryParams.materialId"
          placeholder="请输入物料编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="BOM单编号" prop="bomId">
        <el-input
          v-model="queryParams.bomId"
          placeholder="请输入BOM单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产线编号" prop="productLineId">
        <el-input
          v-model="queryParams.productLineId"
          placeholder="请输入生产线编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工艺编号" prop="processId">
        <el-input
          v-model="queryParams.processId"
          placeholder="请输入工艺编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目编号" prop="projectId">
        <el-input
          v-model="queryParams.projectId"
          placeholder="请输入项目编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产日期" prop="productDate">
        <el-date-picker clearable size="small"
                        v-model="queryParams.productDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择生产日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="交货日期" prop="deliveryDate">
        <el-date-picker clearable size="small"
                        v-model="queryParams.deliveryDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择交货日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="发布状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择发布状态" clearable filterable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:MesProductSchedule:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mes:MesProductSchedule:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mes:MesProductSchedule:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:MesProductSchedule:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="MesProductScheduleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="编号" align="center" prop="id"/>
      <el-table-column label="流水号" align="center" prop="serialNo" show-overflow-tooltip/>
      <el-table-column label="计划号" align="center" prop="planId" show-overflow-tooltip/>
      <el-table-column label="产品" align="center" prop="product" show-overflow-tooltip/>
      <el-table-column label="型号" align="center" prop="model" show-overflow-tooltip/>
      <el-table-column label="规格" align="center" prop="specification" show-overflow-tooltip/>
      <el-table-column label="单位" align="center" prop="unit" show-overflow-tooltip/>
      <el-table-column label="BOM" align="center" prop="bomname" show-overflow-tooltip/>
      <el-table-column label="生产线" align="center" prop="productLine" show-overflow-tooltip/>
      <el-table-column label="工艺" align="center" prop="process" show-overflow-tooltip/>
      <el-table-column label="项目" align="center" prop="projectName" show-overflow-tooltip/>
      <el-table-column label="待产数量" align="center" prop="requireQuantity" show-overflow-tooltip/>
      <el-table-column label="已产数量" align="center" prop="productQuantity" show-overflow-tooltip/>
      <el-table-column label="生产日期" align="center" prop="productDate" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.productDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="交货日期" align="center" prop="deliveryDate" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布状态" align="center" prop="status" :formatter="statusFormat" show-overflow-tooltip/>
      <el-table-column label="领料状态" align="center" prop="receiveStatus" :formatter="receiveStatusFormat"
                       show-overflow-tooltip
      />
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:MesProductSchedule:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mes:MesProductSchedule:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改计划排产对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :inline="true">
        <el-form-item label="计划号" prop="planId">
          <el-select :disabled="form.status == 1" v-model="form.planId" clearable
                     placeholder="请选择计划号"
          >
            <el-option
              v-for="item in formSelect.plan"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目" prop="projectName">
          <el-select :disabled="form.status == 1 || form.status == 0" v-model="form.projectName" clearable
                     placeholder="请选择项目"
          >
            <el-option
              v-for="item in formSelect.project"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品" prop="product">
          <el-select :disabled="form.status == 1 || form.status == 0" v-model="form.product" clearable
                     @change="getFromMaterialInfo(form.product)"
                     placeholder="请选择产品"
          >
            <el-option
              v-for="item in formSelect.product"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格" prop="specification">
          <el-input disabled v-model="form.specification" placeholder="请选择产品"/>
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input disabled v-model="form.model" placeholder="请选择产品"/>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input disabled v-model="form.unit" placeholder="请选择产品"/>
        </el-form-item>
        <el-form-item label="BOM" prop="bomname">
          <el-select :disabled="form.status == 1" v-model="form.bomname" clearable
                     placeholder="请选择BOM"
          >
            <el-option
              v-for="item in formSelect.bom"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生产线" prop="productLine">
          <el-select :disabled="form.status == 1" v-model="form.productLine" clearable
                     placeholder="请选择生产线"
          >
            <el-option
              v-for="item in formSelect.productLine"
              :key="item.product_line_id"
              :label="item.product_line_id"
              :value="item.product_line_id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工艺" prop="process">
          <el-select :disabled="form.status == 1" v-model="form.process" clearable
                     placeholder="请选择工艺"
          >
            <el-option
              v-for="item in formSelect.process"
              :key="item.id"
              :label="item.process_name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="待产数量" prop="requireQuantity">
          <el-input :disabled="form.status == 1 || form.status == 0" v-model="form.requireQuantity"
                    placeholder="请输入待产数量"
          />
        </el-form-item>
        <el-form-item label="已产数量" prop="productQuantity">
          <el-input :disabled="form.status == 1 || form.status == 0" v-model="form.productQuantity"
                    placeholder="请输入已产数量"
          />
        </el-form-item>
        <el-form-item label="生产日期" prop="productDate">
          <el-date-picker :disabled="form.status == 1" clearable size="small"
                          v-model="form.productDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择生产日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="交货日期" prop="deliveryDate">
          <el-date-picker :disabled="form.status == 1 || form.status == 0" clearable size="small"
                          v-model="form.deliveryDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择交货日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group :disabled="form.status == 1 || form.status == 0" v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input :disabled="form.status == 1" v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
        <el-divider content-position="center">排产物料信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddMesProductScheduleMaterial">
              添加
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteMesProductScheduleMaterial">
              删除
            </el-button>
          </el-col>
        </el-row>
        <el-table :data="mesProductScheduleMaterialList" :row-class-name="rowMesProductScheduleMaterialIndex"
                  @selection-change="handleMesProductScheduleMaterialSelectionChange" ref="mesProductScheduleMaterial"
        >
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="物料" prop="material" width="150">
            <template slot-scope="scope">
              <!-- prop 指定表单绑定的对象中需要验证的属性 -->
              <!-- rules 验证的规则可是自定义复杂的规则 -->
              <el-form-item :prop="'mesProductScheduleMaterialList.'+scope.$index+'.material'"
                            :rules="rules.material"
              >
                <el-select @change="getMaterialInfo(scope.$index,mesProductScheduleMaterialList[scope.$index].material)"
                           v-model="mesProductScheduleMaterialList[scope.$index].material" clearable
                           placeholder="请选择物料" :disabled="scope.row.status == 1 || scope.row.status == 0"
                >
                  <el-option
                    v-for="item in materialInfoList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="型号" prop="model" width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'mesProductScheduleMaterialList.'+scope.$index+'.model'">
                <el-input v-model="scope.row.model" disabled
                          placeholder="请输入型号"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="规格" prop="specification" width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'mesProductScheduleMaterialList.'+scope.$index+'.specification'">
                <el-input v-model="scope.row.specification" disabled
                          placeholder="请输入规格"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unit" width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'mesProductScheduleMaterialList.'+scope.$index+'.unit'">
                <el-input v-model="scope.row.unit" disabled
                          placeholder="请输入单位"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="需求数量" prop="requireQuantity" width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'mesProductScheduleMaterialList.'+scope.$index+'.requireQuantity'">
                <el-input v-model="scope.row.requireQuantity" :disabled="scope.row.status == 1 || scope.row.status == 0"
                          placeholder="请输入需求数量"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="已用数量" prop="usageQuantity" width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'mesProductScheduleMaterialList.'+scope.$index+'.usageQuantity'">
                <el-input v-model="scope.row.usageQuantity" :disabled="scope.row.status == 1 || scope.row.status == 0"
                          placeholder="请输入已用数量"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="剩余数量" prop="leftQuantity" width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'mesProductScheduleMaterialList.'+scope.$index+'.leftQuantity'">
                <el-input v-model="scope.row.leftQuantity" :disabled="scope.row.status == 1 || scope.row.status == 0"
                          placeholder="请输入剩余数量"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'mesProductScheduleMaterialList.'+scope.$index+'.remark'">
                <el-input v-model="scope.row.remark" :disabled="scope.row.status == 1" placeholder="请输入备注"/>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addMesProductSchedule,
  delMesProductSchedule,
  exportMesProductSchedule,
  getFormSelect,
  getMesProductSchedule,
  listMesProductSchedule,
  updateMesProductSchedule
} from '@/api/mes/MesProductSchedule'
import { parseTime } from '@/utils/neu'
import { getMaterialInfo, listMaterialInfo } from '@/api/material/materialInfo'

export default {
  name: 'MesProductSchedule',
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedMesProductScheduleMaterial: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 计划排产表格数据
      MesProductScheduleList: [],
      // 排产物料信息表格数据
      mesProductScheduleMaterialList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 发布状态字典
      statusOptions: [],
      // 领料状态字典
      receiveStatusOptions: [],
      // 物料档案列表
      materialInfoList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planId: null,
        materialId: null,
        bomId: null,
        productLineId: null,
        processId: null,
        projectId: null,
        productDate: null,
        deliveryDate: null,
        status: null
      },
      // 表单选项
      formSelect: {
        plan: [],
        project: [],
        product: [],
        bom: [],
        productLine: [],
        process: []
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        planId: [
          { required: true, message: '计划编号不能为空', trigger: 'blur' }
        ],
        bomname: [
          { required: true, message: 'BOM单编号不能为空', trigger: 'blur' }
        ],
        productLine: [
          { required: true, message: '生产线编号不能为空', trigger: 'blur' }
        ],
        process: [
          { required: true, message: '工艺编号不能为空', trigger: 'blur' }
        ],
        requireQuantity: [
          { required: true, message: '待产数量不能为空', trigger: 'blur' }
        ],
        material: [
          { required: true, message: '物料不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getMaterialInfoList()
    this.getDicts('release_status').then(response => {
      this.statusOptions = response.data
    })
    this.getDicts('receive_material_status').then(response => {
      this.receiveStatusOptions = response.data
    })
    this.getFormSelect()
  },
  watch: {
    'mesProductScheduleMaterialList': {
      handler(newVal, oldVal) {
        this.form.mesProductScheduleMaterialList = newVal
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    parseTime,
    /** 查询计划排产列表 */
    getList() {
      this.loading = true
      listMesProductSchedule(this.queryParams).then(response => {
        this.MesProductScheduleList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    getFormSelect() {
      getFormSelect().then(res => {
        this.formSelect = res.data
      })
    },
    getFromMaterialInfo(value) {
      if (value === '') {
        this.form = {
          ...this.form,
          specification: '',
          model: '',
          unit: ''
        }
        return
      }
      getMaterialInfo(value).then(res => {
        this.form = {
          ...this.form,
          specification: res.data.specification,
          model: res.data.model,
          unit: res.data.unit
        }
      })
    },
    getMaterialInfo(index, value) {
      if (value === '') {
        this.mesProductScheduleMaterialList.splice(index, 1)
        return
      }
      getMaterialInfo(value).then(res => {
        this.$set(this.mesProductScheduleMaterialList, index, {
          ...res.data,
          materialId: res.data.id,
          material: res.data.name
        })
      })
    },
    // 获取物料档案
    getMaterialInfoList() {
      listMaterialInfo().then(res => {
        this.materialInfoList = res.rows
      })
    },
    // 发布状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 领料状态字典翻译
    receiveStatusFormat(row, column) {
      return this.selectDictLabel(this.receiveStatusOptions, row.receiveStatus)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.mesProductScheduleMaterialList = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加计划排产'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getMesProductSchedule(id).then(response => {
        this.form = response.data
        this.mesProductScheduleMaterialList = response.data.mesProductScheduleMaterialList
        this.mesProductScheduleMaterialList = response.data.mesProductScheduleMaterialList.map(item => {
          return { ...item, status: this.form.status } // 初始化status状态
        })
        this.open = true
        this.title = '修改计划排产'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMesProductSchedule(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addMesProductSchedule(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除计划排产编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delMesProductSchedule(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 排产物料信息序号 */
    rowMesProductScheduleMaterialIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 排产物料信息添加按钮操作 */
    handleAddMesProductScheduleMaterial() {
      let obj = {}
      obj.materialId = ''
      obj.material = ''
      obj.requireQuantity = ''
      obj.usageQuantity = ''
      obj.leftQuantity = ''
      obj.remark = ''
      obj.status = '2'
      this.mesProductScheduleMaterialList.push(obj)
    },
    /** 排产物料信息删除按钮操作 */
    handleDeleteMesProductScheduleMaterial() {
      if (this.checkedMesProductScheduleMaterial.length == 0) {
        this.$alert('请先选择要删除的排产物料信息数据', '提示', { confirmButtonText: '确定' })
      } else {
        this.mesProductScheduleMaterialList.splice(this.checkedMesProductScheduleMaterial[0].index - 1, 1)
      }
    },
    /** 单选框选中数据 */
    handleMesProductScheduleMaterialSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.mesProductScheduleMaterial.clearSelection()
        this.$refs.mesProductScheduleMaterial.toggleRowSelection(selection.pop())
      } else {
        this.checkedMesProductScheduleMaterial = selection
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有计划排产数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportMesProductSchedule(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    }
  }
}
</script>
